package view;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * Created by eyesee on 2017/5/19.
 */

public class SmoothScrollListview extends ListView implements View.OnKeyListener {
    private int mDuration;
    private ListAdapter mAdapter;
    private int mItemCount;
    private int mItemHeight;

    public SmoothScrollListview(Context context) {
        super(context);
    }

    public SmoothScrollListview(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setOnKeyListener(this);
        this.setSmoothScrollbarEnabled(true);
    }

    public SmoothScrollListview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //滚动动画时间
    public void setScrollDuration(int duration ){
        mDuration = duration;
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);
        this.mAdapter = adapter;
        mItemCount = mAdapter.getCount();                   //item数量
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (mAdapter != null){
            mItemHeight = this.getChildAt(0).getHeight();   //item的高度
        }
    }

    /**记录上一个被选中的item,返回时默认该item被选中*/
    @Override
    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
        int position = getSelectedItemPosition();
        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
        if (gainFocus){
            setSelection(position);
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_UP){
            return false;
        }
        int curPositon = this.getSelectedItemPosition();    //当前被选中的item的position
        if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
            if (curPositon == mItemCount-1){
                setSelection(0);
                return false;
            }
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_UP){
            if (curPositon ==1){
                if (!this.getChildAt(0).isFocusable()){
                    this.smoothScrollBy(-mItemHeight,mDuration);
                }
                return false;
            }else if (curPositon == 0){
                setSelection(mItemCount-1);
                return false;
            }
        }
        return false;
    }
}
